//
//  GamesSetting.m
//  Games
//
//  Created by Sean Chen on 5/9/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "M13FileManager.h"

const NSUInteger kMaxRecordsCount = 20;

@implementation M13FileManager

+ (BOOL)add:(NSObject *)dict toFile:(NSString *)fileName {
    if ([self exits:dict inFile:fileName]) {
        return YES;
    }
    
    NSMutableArray *records = [self recordsInFile:fileName];
    
    if (records.count >= kMaxRecordsCount) {
        [records removeObjectAtIndex:0];
    }
    [records addObject:dict];
    
    NSString *filePath = [self filePathWithFileName:fileName];
    return [records writeToFile:filePath atomically:YES];
}

+ (BOOL)remove:(NSObject *)dict fromFile:(NSString *)fileName {
    if (![self exits:dict inFile:fileName]) {
        return YES;
    }
    
    NSMutableArray *records = [self recordsInFile:fileName];
    [records removeObject:dict];
    
    NSString *filePath = [self filePathWithFileName:fileName];
    return [records writeToFile:filePath atomically:YES];
}

+ (BOOL)exits:(NSObject *)dict inFile:(NSString *)fileName {
    NSMutableArray *records = [self recordsInFile:fileName];
    return [records containsObject:dict];
}

+ (BOOL)fileExits:(NSString *)fileName {
    NSString *filePath = [self filePathWithFileName:fileName];
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}

+ (NSMutableArray *)recordsInFile:(NSString *)fileName {
    if ([self fileExits:fileName]) {
        NSString *filePath = [self filePathWithFileName:fileName];
        NSMutableArray *records = [NSMutableArray arrayWithContentsOfFile:filePath];
        
        return records;
    }
    
    return [NSMutableArray array];
}

+ (NSMutableArray *)reversedRecordsInFile:(NSString *)fileName {
    if ([self fileExits:fileName]) {
        NSString *filePath = [self filePathWithFileName:fileName];
        NSMutableArray *records = [NSMutableArray arrayWithContentsOfFile:filePath];
        
        return [NSMutableArray arrayWithArray:[[records reverseObjectEnumerator] allObjects]];
    }
    
    return [NSMutableArray array];
}

#pragma -

+ (NSString *)filePathWithFileName:(NSString *)fileName {
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Periodicals"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        return [filePath stringByAppendingPathComponent:fileName];
    } else {
        if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:NO attributes:nil error:nil]) {
            //TODO handle this bullshit
        }
        return [filePath stringByAppendingPathComponent:fileName];
    }
}

@end
